package com.cjh.mybatis09.scriping;

import java.util.HashMap;
import java.util.Map;

/**
 * @Descripton 脚本语言注册器
 * @Author cjh
 * @Date 2023/6/12 14:43
 */
public class LanguageDriverRegistry {
    private final Map<Class<?>,LanguageDriver> LANGUAGE_DRIVER_MAP = new HashMap<>();
    private Class<?> defaultDriverClass = null;
    public void register(Class<?> cls){
        if (cls == null) {
            throw new IllegalArgumentException("null is not a valid Language Driver");

        }
        if (!LanguageDriver.class.isAssignableFrom(cls)) {
            throw new RuntimeException(cls.getName() + " does not implements " + LanguageDriver.class.getName());

        }

//        如果没注册过 去注册
        LanguageDriver driver = LANGUAGE_DRIVER_MAP.get(cls);
        if (driver == null) {
            try {
//                单例模式 一个Class 只有一个对应的LanguageDriver
                driver = (LanguageDriver) cls.newInstance();
                LANGUAGE_DRIVER_MAP.put(cls, driver);

            }catch (Exception e){
                throw new RuntimeException("Failed to load language driver for " + cls.getName(), e);

            }
        }
    }

    public LanguageDriver getDriver(Class<?> cls){
        return LANGUAGE_DRIVER_MAP.get(cls);
    }
    public LanguageDriver getDefaultDriver() {
        return getDriver(getDefaultDriverClass());
    }

    public Class<?> getDefaultDriverClass() {

        return defaultDriverClass;
    }

    /**
     * //Configuration()有调用，默认的为XMLLanguageDriver
     * @param defaultDriverClass
     */
    public void setDefaultDriverClass(Class<?> defaultDriverClass){
        register(defaultDriverClass);
        this.defaultDriverClass = defaultDriverClass;
    }
}
